package com.filmatchs.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class NewHttpClientManager {

	public static String LOG_TAG = "NewHttpClientManager";

	public static int METHOD_GET = 1;
	public static int METHOD_POST = 2;
	public static int METHOD_PUT = 3;
	public static int METHOD_DELETE = 4;

	private String result = "";

	/**
	 * Do an HttpClient connection and store the result, the result could be
	 * returned with getResult()
	 * 
	 * @param url
	 * @param method
	 * @param headers
	 * @param entity
	 * @param credential
	 */
	public NewHttpClientManager(String url, int method,
			ArrayList<Header> headers, HttpEntity entity,
			UsernamePasswordCredentials credential)
			throws ClientProtocolException, IOException {
		try {
			result = connectResponse(url, method, headers, entity, credential, null);
		} catch (ClientProtocolException ex) {
			Log.e(LOG_TAG, "ClientProtocol Exception");
			ex.printStackTrace();
		} catch (IOException ex) {
			Log.e(LOG_TAG, "IO Exception");
			ex.printStackTrace();
		}
	}
	
	public NewHttpClientManager(String url, int method,
			ArrayList<Header> headers, HttpEntity entity,
			UsernamePasswordCredentials credential, HttpHost host)
			throws ClientProtocolException, IOException {
		try {
			result = connectResponse(url, method, headers, entity, credential, host);
		} catch (ClientProtocolException ex) {
			Log.e(LOG_TAG, "ClientProtocol Exception");
			ex.printStackTrace();
		} catch (IOException ex) {
			Log.e(LOG_TAG, "IO Exception");
			ex.printStackTrace();
		}
	}

	/**
	 * Do an HttpClient Connection, then returns the result
	 * 
	 * 
	 * @param url
	 * @param method
	 * @param headers
	 * @param entity
	 * @param credential
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String connectResponse(String url, int method,
			List<Header> headers, HttpEntity entity,
			UsernamePasswordCredentials credential, HttpHost host)
			throws ClientProtocolException, IOException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpResponse response;

		String retval = null;

		HttpEntityEnclosingRequest heer = null;

		// setting scheme for http/https
		final SSLSocketFactory sslSocketFactory = SSLSocketFactory
				.getSocketFactory();
		sslSocketFactory
				.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		httpClient.getConnectionManager().getSchemeRegistry().register(
				new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		httpClient.getConnectionManager().getSchemeRegistry().register(
				new Scheme("https", sslSocketFactory, 443));

		if (method == METHOD_POST) {
			// ------------------ POST

			Log.d(LOG_TAG, "POST to " + url);

			heer = new HttpPost(url);

			// Setting Entity if provided
			if (entity != null) {
				Log.d(LOG_TAG, "ENTITY PROVIDED");
				heer.setEntity(entity);
			}

			// Setting Headers if provided
			if (headers != null) {
				Log.d(LOG_TAG, "HEADERS PROVIDED");
				for (Header header : headers) {
					heer.setHeader(header);
				}
			}

			// Setting Credentials if provided
			if (credential != null) {
				Log.d(LOG_TAG, "CREDENTIAL PROVIDED : "
						+ credential.getUserName() + ":"
						+ credential.getPassword());
				httpClient.getCredentialsProvider().setCredentials(
						new AuthScope(AuthScope.ANY), credential);
			}

			// execute the request
			if (host != null) {
				response = httpClient.execute(host, (HttpPost) heer);
			} else {
				response = httpClient.execute((HttpPost) heer);
			}
		} else if (method == METHOD_PUT) {
			// ------------------ PUT
			response = httpClient.execute(new HttpPut(url));
		} else if (method == METHOD_DELETE) {
			// ------------------ DELETE
			response = httpClient.execute(new HttpDelete(url));
		} else {
			// ------------------ GET (DEFAULT: IF NOT POST, PUT, DELETE)
			response = httpClient.execute(new HttpGet(url));
		}

		Log.d(LOG_TAG, "StatusLine " + response.getStatusLine());

		// Setting the response entity
		entity = response.getEntity();

		// if entity is not null, then print it to the return value
		if (entity != null) {
			InputStream instream = entity.getContent();
			String result = StreamManager.convertStreamToString(instream);
			retval = result;
			instream.close();
		}

		// return it!
		return retval;
	}

	/**
	 * Get response of the HttpClient Connection
	 * 
	 * @return
	 */
	public String getResult() {
		return result;
	}
}
